class Cart < ApplicationRecord
  belongs_to :store
  belongs_to :store_customer
  has_many :items, class_name: "CartItem", as: :itemable

  scope :current_cart, ->(store_id, user_id) { where(store_id: store_id, store_customer_id: user_id).last }


  def amount
    items.showable.map{|item| item.amount}.sum
    # items.sum{|item| item.amount}
  end

  def has_item(params)
    @product_id ||= params[:store_product_id]
    @product_ids = items.showable.pluck(:store_product_id)
    if @product_ids.include?(@product_id.to_i)
      add_quantity(@product_id, params[:quantity])
    else
      creater(params)
    end
  end

  def creater(params)
    @cart_item = self.items.new(params)
    if @cart_item.save
      return {status: true, cart_item_id: @cart_item.id}
    else
      return {status: false, message: @cart_item.errors.full_messages.first}
    end
  end

  def add_quantity(product_id, num)
    @cart_item ||= items.showable.exist_item(product_id)
    @cart_item.quantity = @cart_item.quantity + num.to_i
    @cart_item.save
    return {status: true, cart_item_id: @cart_item.id}
  end

  def items_count
    items.showable.count(:id)
  end

  def customable_products
    self.items.showable.customs
  end

  def customable_product_count
    customable_products.count
  end
end
